package com.stu.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stu.bean.Goods;
import com.stu.bean.Orders;

import com.stu.service.OrdersService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @RequestMapping("/getOrders")
    @ResponseBody
    public Object getAllOrders(Orders orders, Date strDate, Date endDate, @RequestParam(value = "pageSize",required = false,defaultValue = "3") int pageSize, @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum){
        System.out.println(pageSize);
        System.out.println("页码"+pageNum);
        PageHelper.startPage(pageNum,pageSize);
        Page<Orders> orders1 = (Page<Orders>)ordersService.getOrders(orders,strDate,endDate);
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(orders1,5);
        return pageInfo;

    }

    @RequestMapping(value = "/orders/{oid}",method = RequestMethod.DELETE)
    @ResponseBody
    public int deleteOrders(@PathVariable("oid") int oid){
        return ordersService.deleteOrder(oid);
    }

    @RequestMapping("/insertDd")
    public String goodsRegister(@Valid Orders orders, MultipartFile ordersimg, Model model, BindingResult bindingResult, HttpSession session) throws IOException {
        System.out.println(orders);

        System.out.println(ordersimg);
        if(bindingResult.hasErrors()){
            Map<String,String> map = new HashMap<String, String>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for(FieldError fieldError:fieldErrors){
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errors",map);
            return "order";
        }
        String imgPath = "c:/images/";
        String imgName = new Date().getTime()+ordersimg.getOriginalFilename();
        File file = new File(imgPath+imgName);
        ordersimg.transferTo(file);
        orders.setOimg("/images/"+imgName);

        Orders orders1 = ordersService.insertDd(orders);
        System.out.println(orders1);
        if(orders1!=null){
            session.setAttribute("insertDd",orders1);
            return "order";
        }else{
            return "order";
        }
    }
}
